import _ from 'lodash';

import { OPERATE_TYPE } from '../constants/publicConstant';

const tokenKey = 'anygateway-token';

let currentToken = '';
let currentResourceId = '';

export const getOptions = (children: any[], fieldNames?: any) => {
  const $children = _.get(children, '[0].children');

  if ($children) {
    children = $children;
  }

  const { value, label, labelFunc } = fieldNames || {
    value: 'value',
    label: 'label',
  };
  return _.map(children, (item) => {
    if (_.isString(item)) {
      return {
        value: item,
        label: item,
      };
    }

    const l = item[label];
    const v = item[value];

    return {
      // label: `${item[value]} - ${item[label]}`,
      value: v,
      label: labelFunc ? labelFunc(v, l) : l === v ? v : [v, l].join(' - '),
    };
  });
};

export const getUrlParams = () => {
  const result: any = {};
  const query = window.location.search.substring(1);
  const vars = query.split('&');
  for (let i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');
    result[pair[0]] = pair[1];
  }
  return result;
};

export const getQueryStringByObject = (o: any) => {
  if (_.isObject(o)) {
    return _.map(o, (value, key) =>
      [key, encodeURIComponent(_.isObject(value) ? JSON.stringify(value) : value)].join('='),
    ).join('&');
  } else {
    return o;
  }
};

export const formatUrl = (url: string, config: any) => {
  _.each(config, (value, key) => {
    url = url.replace(`{${key}}`, value);
  });
  return url;
};

export const getResponseData = (response: any) => {
  return response;
};

export const saveToken = (token: string) => {
  currentToken = token;
  localStorage.setItem(tokenKey, token);
};

export const getToken = () => {
  return currentToken || localStorage.getItem(tokenKey);
};

export const clearToken = () => {
  currentToken = '';
  localStorage.removeItem(tokenKey);
};

export const logout = (loginUrl: string) => {
  // if (IS_DEV) return;

  clearToken();
  window.location.href = loginUrl;
};

export const saveResourceId = (resourceId: string) => {
  currentResourceId = resourceId;
};

export const getResourceId = () => {
  return currentResourceId;
};

export const getPageData = (data = { page: 1, rows: 10, total: 0 }): any => {
  return {
    current: data?.page,
    pageSize: data?.rows,
    total: data?.total,
  };
};

export const formatRequestData = (data: any) => {
  return _.extend({ organizationNumber: '156' }, data);
};
/**
 * 参数页面通用处理接口参数
 */
export const getRequestData = (postData: any, type: string, rowData: any): object => {
  let otherParam = {};
  switch (type) {
    case OPERATE_TYPE.edit: {
      // 编辑带入版本号和参数状态
      const { version, paramSts } = rowData;
      otherParam = { version, paramSts };
      break;
    }
    case OPERATE_TYPE.create:
      return { ...otherParam, ...postData.formData };
    default:
      return { ...postData };
  }
  return { ...otherParam, ...postData.formData };
};
